package com.authorityManagement.filter;

import com.authorityManagement.entity.LoginUser;
import com.authorityManagement.exception.CustomerExceptionHandler;
import com.authorityManagement.service.impl.UserDetailsServiceImpl;
import com.authorityManagement.util.jwtUtil.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class TokenCheckFilter extends OncePerRequestFilter {
      
      @Autowired
      private HandlerExceptionResolver handlerExceptionResolver;
      
      @Autowired
      private UserDetailsServiceImpl userDetailsService;
      
      @Autowired
      private RedisTemplate redisTemplate;
      
      
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            String token = request.getHeader("token");
            if (Objects.isNull(token)) {
                  token = request.getParameter("token");
            }
            if (token == null) {
                  filterChain.doFilter(request, response);
                  return;
            }
      
            String redisToken = (String) redisTemplate.opsForValue().get("token:" + token);
            if (!StringUtils.hasText(redisToken)) {
                  handlerExceptionResolver.resolveException(request, response, null, new CustomerExceptionHandler("用户未登录"));
                  return;
            }
      
            if (!token.equals(redisToken)) {
                  handlerExceptionResolver.resolveException(request, response, null, new CustomerExceptionHandler("token不合法"));
                  return;
            }
      
            String userId = null;
            String userName = null;
            try {
                  Claims claims = JwtUtil.parseJWT(token);
                  userId = claims.getSubject();
                  userName = (String) claims.get("userName");
            } catch (Exception e) {
                  handlerExceptionResolver.resolveException(request, response, null, new CustomerExceptionHandler("token不合法"));
                  return;
            }
      
            LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(userName);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request, response);
      }
}
